package com.zjf.config;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan("com.zjf.dao")
public class MyBatisConfig {

    @Bean
    public SqlSessionFactory newSqlSessionFactoryBean(DataSource dataSource) throws Exception {
        //需要使用MybatisSqlSessionFactoryBean 而不是 SqlSessionFactoryBean
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        //配置完下面这两个在 application.properties 就不需要配置了
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/zjf/dao/mapper/*.xml"));
        bean.setTypeAliasesPackage("com.zjf.domain.entity");

        //configuration 需要使用 MybatisConfiguration 如果使用 org.apache.ibatis.session.Configuration 也有可能会报错
        MybatisConfiguration configuration = new MybatisConfiguration();

        // 返回类型Map时字段为空也要返回字段名称
        configuration.setCallSettersOnNulls(true);
        //驼峰命名映射
        configuration.setMapUnderscoreToCamelCase(false);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }


}
